/**
 * 
 */
package de.cbf.cam.dsa.battle.logic.commands;

import java.util.ArrayList;
import java.util.List;

import de.cbf.cam.dsa.battle.exceptions.ParseCommandException;
import de.cbf.cam.dsa.model.entities.states.stateChanger.StateChangerBase;

/**
 * @author Nebelritter
 *
 */
public class CommandParser {
	/**
	 * @uml.property  name="commands"
	 * @uml.associationEnd  multiplicity="(0 -1)" elementType="de.cbf.cam.dsa.battle.logic.commands.OneCommandBase"
	 */
	private List<OneCommandBase> commands = new ArrayList<OneCommandBase>();
//========================
//		constructors
//========================
	/**
	 * method to initialize object,
	 * provide default values for every field
	 * accessable by all constructors
	 */
	private void init() {
		addCommand(new OneCommandChangeLE());
		addCommand(new OneCommandChangePosition());
		addCommand(new OneCommandChangeINI());
		addCommand(new OneCommandChangeAT());
	}
	public CommandParser() {
		super();
		init();
	}
//========================
//	   public methods
//========================
	public List<StateChangerBase> parseCommand(String command,int index) throws ParseCommandException {		
		//parse commands
		List<StateChangerBase> stateChangersResult = new ArrayList<StateChangerBase>();
		int firstIndex = index;
		int lastIndex;
		
		while(index<command.length()){	
			boolean recognised=false;
			lastIndex = command.indexOf(" ",firstIndex+1);
			if(lastIndex<0) return stateChangersResult;//no more spaces -> no more commands-> return 
			//get command
			String oneCommand=command.substring(firstIndex+1,lastIndex);
			//if somebody put in a space to much
			if(oneCommand.equals("")){
				recognised=true;
			}
			//decide command
			for(int i=0;i<commands.size();i++){
				if(oneCommand.startsWith(commands.get(i).getName())){
					//seemingly found command
					stateChangersResult.addAll(commands.get(i).evaluateCommand(oneCommand));
					recognised=true;
				}
			}		
			//error if command not recognized
			if(!recognised){
				throw new ParseCommandException("Command not recognised:"+oneCommand);
			}
			
			firstIndex=lastIndex;
		}	
		return stateChangersResult;
	}

//========================
//    standard methods
//========================

//========================
// 	   private methods
//========================

//========================
// 	SHORT property access
//========================

//========================
//		getters
//========================

//========================
//		setters
//========================
	public void addCommand(OneCommandBase command){
		commands.add(command);
	}
//========================
//		listeners
//========================

}
